package com.welab.pandahelper.activity;

import static com.welab.pandahelper.utils.taskUtils.getCatGifts;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.google.gson.Gson;
import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;
import com.welab.pandahelper.R;
import com.welab.pandahelper.adapter.AppsListAdapter;
import com.welab.pandahelper.bean.CustomDialog;
import com.welab.pandahelper.bean.ExpandableListItem;
import com.welab.pandahelper.bean.MyResponse;
import com.welab.pandahelper.config.MyConfig;
import com.welab.pandahelper.utils.taskUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

public class CatHelperActivity extends AppCompatActivity implements TextWatcher {


    private static SharedPreferences mPrefs;
    private EditText phone_text;
    private EditText passwd_text;
    private Button start_task;
    private TextView txtAppSelected;

    private static Boolean startFlag;
    private static Boolean exitFlag;
    private Button check_passwd;
    private com.welab.pandahelper.utils.codeUtils codeUtils;
    private String goodId = "1393873104310583298";
    private ArrayList<ExpandableListItem> mGift;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cathelper);
        startFlag = false;
        exitFlag = false;
        check_passwd = (Button)findViewById(R.id.check_passwd);
        phone_text = (EditText) findViewById(R.id.edit_phone);
        phone_text.addTextChangedListener(this);
        passwd_text = (EditText) findViewById(R.id.passwd);
        start_task = (Button) findViewById(R.id.start_task);
        txtAppSelected = (TextView) findViewById(R.id.txtAppSelected);
        mPrefs = getApplicationContext().getSharedPreferences("cat_token", Context.MODE_PRIVATE);


        check_passwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = phone_text.getText().toString();
                String passwd = passwd_text.getText().toString();
                if (!passwd.equals("")){
                    codeUtils.setCodeType("cat");
                    codeUtils.getToken(CatHelperActivity.this,passwd,phone);
                }else {
                    Toast.makeText(CatHelperActivity.this,"请输入密码后认证！",Toast.LENGTH_SHORT).show();
                }
                initGifts();
            }
        });


        start_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = phone_text.getText().toString();
                String token = mPrefs.getString(phone,"0");
                if ("0".equals(token)){
                    Toast.makeText(CatHelperActivity.this,"请先输入密码进行认证后开始任务！！！",Toast.LENGTH_LONG).show();
                }else {
                    start_task.setText("xxxx");
                    start_task.setClickable(false);
                    startFlag = true;
                    getCatTask(CatHelperActivity.this,token);
                }
            }
        });
    }


    public void onPickAppClick(View v) {
        if ( mGift == null || mGift.size() < 1){
            Toast.makeText(CatHelperActivity.this,"请先输入密码进行认证后选择任务！",Toast.LENGTH_LONG).show();
            return;
        }
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_apps_list)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.getView(R.id.confirm_btn).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        holder.getView(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                        ListView lv = holder.getView(R.id.apps_lv);
                        lv.setAdapter(new AppsListAdapter(dialog.getContext(), mGift));
                        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                ExpandableListItem item = (ExpandableListItem) parent.getAdapter().getItem(position);
                                if (item != null) {
                                    txtAppSelected.setText(item.getAppName());
                                    goodId = item.getPckName();
                                }

                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setHeight(520)
                .show(getSupportFragmentManager());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    private void initGifts() {
        String phone = phone_text.getText().toString();
        String token = mPrefs.getString(phone,"0");
        if ("0".equals(token)){
            Toast.makeText(CatHelperActivity.this,"请先输入密码进行认证后选择礼品！！！",Toast.LENGTH_LONG).show();
        }else {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        mGift = getCatGifts(token);
                        Collections.sort(mGift, new Comparator<ExpandableListItem>() {
                            public int compare(ExpandableListItem o1, ExpandableListItem o2) {
                                return o1.getAppName().compareTo(o2.getAppName());
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }



    public void getCatTask(Context context,String token){

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (startFlag){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        MyResponse myResponse = taskUtils.getCatTaskList(token,goodId);
                        List<Map<String,Object>> giftList = (List<Map<String, Object>>) ((Map<String,Object>)myResponse.getData()).get("records");
                        if (giftList != null && giftList.size() > 0){
                            for (Map<String,Object> gift:giftList
                            ) {
                                if (gift.get("goodsId").equals(goodId)){
                                    String id = (String)gift.get("id");
                                    Long times = Long.valueOf((String) gift.get("times"));
                                    Log.e(MyConfig.APP_NAME,times+"");
                                    if (times > 12000){
                                        Thread.sleep(10000);
                                        break;
                                    }
                                    Thread.sleep(times-1);
                                    MyResponse myResponse1  = taskUtils.getCatTask(token,id,goodId);
                                    if (myResponse1.getMsg().equals("success")){
                                        startFlag = false;
                                    }else{
                                        Toast.makeText(context,myResponse1.getMsg(),Toast.LENGTH_SHORT).show();
                                        Log.e(MyConfig.APP_NAME,myResponse1.getMsg());
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        start_task.setText("抢单中,请勿离开此页面，最好别动---");

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                CustomDialog mDialog=new CustomDialog(CatHelperActivity.this, "温馨提示", "抢单成功！！?", "确定",new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                mDialog.dismiss();
                        Toast.makeText(CatHelperActivity.this,"抢到单了--开心赚钱",Toast.LENGTH_LONG).show();
                        Intent i = new Intent(CatHelperActivity.this,MainActivity.class);
                        startActivity(i);
                        finish();
                    }
                });
                mDialog.setCanotBackPress();
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.show();
            }
        };

        new Thread(){
            @Override
            public void run() {
                try {
                    while (startFlag){
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!exitFlag){
                        Message message = new Message();
                        message.obj = true;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Toast.makeText(CatHelperActivity.this,"抢单成功后会弹窗提示！！！",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        //将线程销毁掉
        super.onDestroy();
        startFlag = false;
        exitFlag = true;
    }
}

